// components/player/index.js
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    songInfo: {
      type: Object,
      observer: function (newVal, oldVal) {
        this.setData({
          songInfo: newVal
        })
        // console.log(newVal)
        //
        if (oldVal == null || newVal._id != oldVal._id) {
          this.ReqLyric(newVal.mid)
        }
        //

        let audio = wx.getBackgroundAudioManager();
        audio.src = 'https://api.bbbug.com/api/song/playurl?mid=' + newVal.mid
        audio.title = newVal.name + ' - ' + newVal.singer;
        audio.coverImgUrl = newVal.pic
        audio.webUrl = newVal.pic;
        audio.play()

      }
    },
    inchat: {
      type: Boolean
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    songInfo: null,
    musicLrcObj: null,
    lrcString: '',
    simplePlayer: true
  },
  lifetimes: {
    attached() {
      var that = this;
      let audio = wx.getBackgroundAudioManager();
      audio.onTimeUpdate(function (e) {
        if (that.data.songInfo) {
          wx.getBackgroundAudioPlayerState({
            success(res) {
              // console.log(res)
              if (that.data.musicLrcObj && res.status == 1) {
                for (let i = 0; i < that.data.musicLrcObj.length; i++) {
                  if (i == that.data.musicLrcObj.length - 1) {
                    that.setData({
                      lrcString: that.data.musicLrcObj[i].lineLyric
                    });
                    return;
                  } else {
                    if (res.currentPosition + 1 > that.data.musicLrcObj[i].time && res.currentPosition < that.data.musicLrcObj[i + 1].time) {
                      that.setData({
                        lrcString: that.data.musicLrcObj[i].lineLyric
                      });
                      return;
                    }
                  }
                }
              }
            }
          });
        }
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    ReqLyric(mid) {

      var that = this;
      wx.request({
        url: "https://api.bbbug.com/api/song/getLrc",
        loading: "搜索中",
        data: {
          mid: mid
        },
        success: function (res) {
          console.log(res)
          that.setData({
            musicLrcObj: res.data.data,
            lrcString: "歌词加载中..."
          });
        }
      });
    },
    toggleplayer() {
      this.setData({
        simplePlayer: !this.data.simplePlayer
      })
    }
  }
})